<template>
	<view class="upload">
		<view class="upload-lists">
			<view class="upload-list" v-for="(item,index) of uploadLists" :key="index">
				<image @click="seeImg(index)" :src="item.url" mode="aspectFill"></image>
				<text v-if="!isDisabled" class="iconfont icon-upload-del" @click="clearImg(item.url)"></text>
			</view>
			<view v-if="uploadLists.length<6 && !isDisabled" class="upload-btn" @click="upload()">
				<text class="iconfont icon-upload-icon"></text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "BlockUpload",
		props:{
			isDisabled:{
				type:Boolean,
				default:true
			},
			uploadFiles:{
				type: [Array],
				default () {
					return []
				}
			}
		},
		data() {
			return {
				uploadLists: [],
				seeFiles:[],
			};
		},
		methods: {
			upload() {
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						const uploadTask = uni.uploadFile({
							url:this.$baseURL+'/api/upload/uploadImg',
							filePath: tempFilePaths[0],
							name: 'file',
							header: {
								'Authorization': uni.getStorageSync('oauth_token')
							},
							success: (uploadFileRes) => {
								let res = JSON.parse(uploadFileRes.data);
								if(res.code === 1){
									this.uploadLists.push(res.data);
									this.seeFiles.push(res.data.url);
									uni.hideLoading()
								}
							}
						});

						uploadTask.onProgressUpdate((res) => {
							uni.showLoading({
							    title: '上传中...',
								mask:true
							});
							if(this.uploadFiles.length>=6){
								uploadTask.abort();
								uni.hideLoading()
							}
							// console.log('上传进度' + res.progress);
							// console.log('已经上传的数据长度' + res.totalBytesSent);
							// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
							if (res.progress > 5000) {
								uploadTask.abort();
							}
						});
					}
				});
			},
			clearImg(url){
				this.uploadLists = this.uploadLists.filter(item=>{
					return item.url !== url
				})
				this.seeFiles = this.seeFiles.filter(item=>{
					return item !== url
				})
			},
			seeImg(index) {
				uni.previewImage({
					current: index, //预览图片的下标
					urls: this.seeFiles, //预览图片的地址，必须要数组形式，如果不是数组形式就转换成数组形式就可以
				})
			},
		},
		computed: {

		},
		watch: {
			uploadFiles(newValue){
				this.uploadLists = newValue;
				for(let item of newValue){
					this.seeFiles.push(item.url);
				}
			},
			uploadLists(){
				this.$emit("uploadFiles",this.uploadLists)
			}
		},
	};
</script>

<style lang="less" scoped src="./BlockUpload.less">
</style>
